package com.cspg.design.ui.project;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.cspg.design.CSPGApplication;
import com.cspg.design.R;
import com.cspg.design.bean.deviceBean.PointDeviceBean;
import com.cspg.design.bean.deviceBean.PolylineDeviceBean;
import com.cspg.design.bean.modelLibrary.TransformerLibrary;
import com.cspg.design.bean.modelLibrary.WireLibrary;
import com.cspg.design.bean.projectBean.ProjectBean;
import com.cspg.design.dao.gen.DaoSession;
import com.cspg.design.dao.gen.PointDeviceBeanDao;
import com.cspg.design.dao.gen.PolylineDeviceBeanDao;
import com.cspg.design.dao.gen.ProjectBeanDao;
import com.cspg.design.dao.gen.TransformerLibraryDao;
import com.cspg.design.dao.gen.WireLibraryDao;
import com.cspg.design.utils.ActionBarUtil;
import com.cspg.design.utils.StatusBarUtil;
import com.cspg.design.utils.Utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class ProjectTotal extends AppCompatActivity {

    private TableLayout tableLayout_tower;
    private TableLayout tableLayout_transformer;
    private TableLayout tableLayout_wire;
    private Double cost = 0D;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project_total);
        StatusBarUtil.setStatusBarColor(this, R.color.colorPrimary);
        ActionBarUtil.setActionBar(this, R.string.project_total);
//        ActionBarUtil.setActionBarRightBtn(this,R.string.project_total, R.layout.action_bar_right_btn);
//        Button export_btn = getSupportActionBar().getCustomView().findViewById(R.id.bar_btn_export);
//        export_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Toast.makeText(ProjectTotal.this,"导出内容",Toast.LENGTH_SHORT).show();
//            }
//        });
        tableLayout_tower = findViewById(R.id.ty_tower);
        tableLayout_wire = findViewById(R.id.ty_wire);
        tableLayout_transformer = findViewById(R.id.ty_transformer);
        initData();
    }

    private void initData() {
        DaoSession daoSession = ((CSPGApplication) getApplication()).getDaoSession();
        String projectId = getIntent().getStringExtra("projectId");
        ProjectBean projectBean = daoSession
                .getProjectBeanDao().queryBuilder().where(ProjectBeanDao.Properties.ProjectId.eq(projectId)).unique();
        daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.ProjectId.eq(projectId),
                PointDeviceBeanDao.Properties.PointType.eq(1)).rx()
                .list().observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<PointDeviceBean>>() {
                    @Override
                    public void call(List<PointDeviceBean> pointDeviceBeans) {
                        TextView tvPole = findViewById(R.id.tv_project_total_pole);
                        tvPole.setText(pointDeviceBeans.size() + "");
                        List<String> models = new ArrayList<>();
                        for (int i = 0; i < pointDeviceBeans.size(); i++) {
                            String model = pointDeviceBeans.get(i).getPointModel();
                            if (!models.contains(model)) {
                                models.add(model);
                            }
                        }
                        Map<String, Integer> hashMap = new HashMap<>();
                        for (int i = 0; i < pointDeviceBeans.size(); i++) {
                            String model = pointDeviceBeans.get(i).getPointModel();
                            int index = models.indexOf(model);
                            model = models.get(index);
                            Integer integer = hashMap.get(model);
                            if (integer == null) {
                                hashMap.put(model, 1);
                            } else {
                                hashMap.put(model, integer + 1);
                            }
                        }
                        for (int i = 0; i < models.size(); i++) {
                            TableRow tableRow = new TableRow(ProjectTotal.this);
                            TextView textViewModel = new TextView(ProjectTotal.this);
                            textViewModel.setText(models.get(i));
                            textViewModel.setBackgroundResource(R.drawable.black_frame);
                            textViewModel.setPadding(10, 10, 10, 10);
                            tableRow.addView(textViewModel);
                            TextView textViewNum = new TextView(ProjectTotal.this);
                            textViewNum.setText(hashMap.get(models.get(i)).toString());
                            textViewNum.setBackgroundResource(R.drawable.black_frame);
                            textViewNum.setPadding(10, 10, 10, 10);
                            tableRow.addView(textViewNum);
                            tableLayout_tower.addView(tableRow);
                        }

                    }
                });
        List<PointDeviceBean> transformerBeans = daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.ProjectId.eq(projectId),
                PointDeviceBeanDao.Properties.PointType.eq(3))
                .list();
        if (transformerBeans != null) {
            TextView tvtTransformer = findViewById(R.id.tv_project_total_transformer);
            tvtTransformer.setText(transformerBeans.size() + "");
            int capacity = 0;
            List<String> models = new ArrayList<>();
            for (int i = 0; i < transformerBeans.size(); i++) {
                String model = transformerBeans.get(i).getPointModel();
                if (!models.contains(model)) {
                    models.add(model);
                }
                if (model == null || model.isEmpty()) {
                    continue;
                }
                List<TransformerLibrary> transformerLibrarys = daoSession.getTransformerLibraryDao().queryBuilder()
                        .where(TransformerLibraryDao.Properties.TransformerModel.eq(model)).list();
                if (transformerLibrarys.size() > 0) {
                    TransformerLibrary transformerLibrary = transformerLibrarys.get(0);
                    capacity += Integer.parseInt(transformerLibrary.getCapacity());
                    String transformerCost = transformerLibrary.getCost();
                    if (transformerCost != null) {
                        if (Utils.isDouble(transformerCost)) {
                            cost += Double.parseDouble(transformerCost);
                        } else if (Utils.isInteger(transformerCost)) {
                            cost += Integer.parseInt(transformerCost);
                        }
                    }
                }

            }
            ((TextView) findViewById(R.id.tv_project_total_transformer)).setText(String.valueOf(capacity));
            Map<String, Integer> hashMap = new HashMap<>();
            for (int i = 0; i < transformerBeans.size(); i++) {
                String model = transformerBeans.get(i).getPointModel();
                int index = models.indexOf(model);
                model = models.get(index);
                Integer integer = hashMap.get(model);
                if (integer == null) {
                    hashMap.put(model, 1);
                } else {
                    hashMap.put(model, integer + 1);
                }
            }
            for (int i = 0; i < models.size(); i++) {
                TableRow tableRow = new TableRow(ProjectTotal.this);
                TextView textViewModel = new TextView(ProjectTotal.this);
                textViewModel.setText(models.get(i));
                textViewModel.setBackgroundResource(R.drawable.black_frame);
                textViewModel.setPadding(10, 10, 10, 10);
                tableRow.addView(textViewModel);
                TextView textViewCapacity = new TextView(ProjectTotal.this);
                List<TransformerLibrary> transformerLibraries = daoSession.getTransformerLibraryDao()
                        .queryBuilder().where(TransformerLibraryDao.Properties.PoleModel.eq(textViewModel.getText().toString()))
                        .list();
                if (transformerLibraries != null && transformerLibraries.size() > 0 &&  transformerLibraries.get(0) != null)
                {
                    TransformerLibrary transformerLibrary = transformerLibraries.get(0);
                    if (transformerLibrary != null)
                    {
                        textViewCapacity.setText(transformerLibrary.getCapacity());
                    }
                }else {
                    textViewCapacity.setText("无数据");
                }
                textViewCapacity.setBackgroundResource(R.drawable.black_frame);
                textViewCapacity.setPadding(10, 10, 10, 10);
                tableRow.addView(textViewCapacity);

                TextView textViewNum = new TextView(ProjectTotal.this);
                textViewNum.setText(hashMap.get(models.get(i)).toString());
                textViewNum.setBackgroundResource(R.drawable.black_frame);
                textViewNum.setPadding(10, 10, 10, 10);
                tableRow.addView(textViewNum);
                tableLayout_transformer.addView(tableRow);
            }
        }
        List<PolylineDeviceBean> polylineDeviceBeans = daoSession.getPolylineDeviceBeanDao()
                .queryBuilder().where(PolylineDeviceBeanDao.Properties.ProjectId.eq(projectId))
                .list();
        if (polylineDeviceBeans != null) {
            Double totalDistance = 0D;
            Map<String, Double> map = new HashMap<>();
            for (int i = 0; i < polylineDeviceBeans.size(); i++) {
                PolylineDeviceBean deviceBean = polylineDeviceBeans.get(i);
                Double distance = DistanceUtil.getDistance(
                        new LatLng(deviceBean.getStartLatitude(), deviceBean.getStartLongitude()),
                        new LatLng(deviceBean.getEndLatitude(), deviceBean.getEndLongitude()));
                distance = new BigDecimal(distance).setScale(2, RoundingMode.UP).doubleValue();
                totalDistance += distance;
                if (map.get(deviceBean.getPolylineModel()) == null) {
                    map.put(deviceBean.getPolylineModel(), distance);
                } else {
                    Double value = map.get(deviceBean.getPolylineModel());
                    value += distance;
                    map.put(deviceBean.getPolylineModel(), value);
                }
                List<WireLibrary> wireLibrarys = daoSession.getWireLibraryDao().queryBuilder()
                        .where(WireLibraryDao.Properties.WireModel.eq(deviceBean.getPolylineModel()))
                        .list();
                if (wireLibrarys.size() > 0) {
                    WireLibrary wireLibrary = wireLibrarys.get(0);
                    String polylineCost = wireLibrary.getCostPerKM();
                    if (polylineCost != null) {
                        if (Utils.isDouble(polylineCost)) {
                            cost += Double.parseDouble(polylineCost) * distance / 1000;
                        } else if (Utils.isInteger(polylineCost)) {
                            cost += Integer.parseInt(polylineCost) * distance / 1000;
                        }
                    }
                }
            }

            Set<String> set = map.keySet();
            for (String str : set) {
                TableRow tableRow = new TableRow(ProjectTotal.this);
                TextView textViewModel = new TextView(ProjectTotal.this);
                textViewModel.setText(str);
                textViewModel.setBackgroundResource(R.drawable.black_frame);
                textViewModel.setPadding(10, 10, 10, 10);
                tableRow.addView(textViewModel);
                TextView textViewNum = new TextView(ProjectTotal.this);
                textViewNum.setText(map.get(str).toString());
                textViewNum.setBackgroundResource(R.drawable.black_frame);
                textViewNum.setPadding(10, 10, 10, 10);
                tableRow.addView(textViewNum);
                tableLayout_wire.addView(tableRow);
            }
            totalDistance = totalDistance / 1000;
            totalDistance = new BigDecimal(totalDistance).setScale(4, RoundingMode.UP).doubleValue();
            ((TextView) findViewById(R.id.et_project_total_wire)).setText(totalDistance.toString());
            cost = new BigDecimal(cost).setScale(4, RoundingMode.UP).doubleValue();
            ((TextView) findViewById(R.id.tv_project_total_cost)).setText(cost.toString());
        }
    }

}